package calvin.study.rabbitmq.config;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeoutException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * @ClassName:RabbitMqConnection   
 * @Description:获取mq连接
 * @author:Calvin.W
 * @date:2022年1月7日 上午9:46:25
 */
public class RabbitMqConnection {
	
	private final static Logger log = LoggerFactory.getLogger(RabbitMqConnection.class);
	
	protected List<Connection> mqConnections = new ArrayList<Connection>();
	
	private static RabbitMqConnection rabbitMqConnection;
	
	/**
	 * @Title: getInstance   
	 * @Description: 单例模式（懒汉式），线程安全
	 * @date: 2022年1月7日 上午9:42:24   
	 * @version:
	 * @return          
	 * @throws
	 */
	public static RabbitMqConnection getInstance(){
		if(null == rabbitMqConnection){
			//保证线程安全
			synchronized (RabbitMqConnection.class) {
				if(rabbitMqConnection == null){
					rabbitMqConnection = new RabbitMqConnection();
				}
			}
		}
		return rabbitMqConnection;
	}

	private RabbitMqConnection() {
		mqConnections.clear();
		
		String hosts[] = {"10.3.1.163"};
		ConnectionFactory factory = null;
		for(String host : hosts) {
			factory = new ConnectionFactory();
			factory.setHost(host);
			factory.setPort(Integer.valueOf("5672"));
			factory.setUsername("guest");
			factory.setPassword("guest");
			factory.setVirtualHost("calvin_virtual_host");
			Connection conn = null;
			try {
				conn = factory.newConnection();
			} catch (TimeoutException e) {
				log.error(e.getMessage());
			} catch (IOException e) {
				log.error(e.getMessage());
			}
			mqConnections.add(conn);
		}
	}

	public List<Connection> getMqConnections() {
		return mqConnections;
	}
}
